package com.mengxiang.itman.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletContext
 */
public class ChatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletConfig sc=getServletConfig();
		String charset=sc.getInitParameter("charset");
		request.setCharacterEncoding(charset);
		response.setContentType("text/html;UTF-8");
		PrintWriter out=response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		String ip=request.getLocalAddr();
		
		SimpleDateFormat sd=new SimpleDateFormat("HH:mm:ss");
		String tm=sd.format(new Date());
		String form="<form action='chat' method='post'>"+
				   "Msg:<input type='text' name='msg'/>"+
				   "<input type='submit' value='发送'/>"+
				   "</form>";
//		"<from action='chat' method='post'>"+
//				"MSG:<input type='text' name='msg' />"+
//				"<input type='submit' value='发言'/>"+
//				"</from>";
		
		
		String msg=request.getParameter("msg");
		if(msg!=null&& !msg.trim().equals("")){
			String msgs=(String) getServletContext().getAttribute("msgs");
			//msgs+=">>"+tm+">>"+ip+"<br/>"+msg;
			msgs=tm+"&nbsp;&nbsp;"+ip+">>"+msg+"<br/>"+msgs;
			getServletContext().setAttribute("msgs", msgs);
		}
//		//接收用户的信息
//				String msg = request.getParameter("msg");
//				if(msg!=null && !msg.trim().equals("")){
//					//放到ServletContext中去
//					String msgs = (String) getServletContext().getAttribute("msgs");
//					msgs=tm+"&nbsp;&nbsp;"+ip+":"+msg+"<br/>"+msgs;
//					getServletContext().setAttribute("msgs",msgs);
//				}
		//String div="<div style='border:1px solid:red;width:600px;height:400px;overflow:auto;'>";
		String div="<div style='border:1px solid red;width:600px;height:400px;overflow:auto;'>";
		div+=getServletContext().getAttribute("msgs");
		div+="</div>";
		out.print(form);
		out.print("<hr/>");
		out.print(div);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}
